package ca.ericslandry.server.handler;

import javax.servlet.http.HttpSession;

import net.customware.gwt.dispatch.server.ExecutionContext;
import net.customware.gwt.dispatch.shared.ActionException;

import org.apache.commons.logging.Log;

import ca.ericslandry.server.dao.UserDAO;
import ca.ericslandry.shared.domain.User;
import ca.ericslandry.shared.rpc.UserSave;
import ca.ericslandry.shared.rpc.UserSaveResult;

import com.google.inject.Inject;
import com.google.inject.Provider;

public class SaveUserHandler extends BaseSessionHandler<UserSave, UserSaveResult> {
	@Inject
	public SaveUserHandler(Log logger, Provider<HttpSession> sessionProvider) {
		super(logger, sessionProvider);
	}

	@Override
	public UserSaveResult executeInternal(UserSave action, ExecutionContext context) throws ActionException {
		User currentUser = getUser();
		User userToSave = action.getUser();
		if (!currentUser.getId().equals(userToSave.getId())) {
			throw new ActionException("Can't change details of another user.");
		}
		UserDAO dao = new UserDAO();
		dao.put(userToSave);
		return new UserSaveResult(action.getUser());
	}

	@Override
	public Class<UserSave> getActionType() {
		return UserSave.class;
	}
}
